<template>
  <div class="page-fs">
    <common-query-tool
      :list-query-params="rule.queryParams"
      :init-list="initList"
      :click-add="handleUpdate"
    />
    <ATable
      class="table-content"
      :data-source="list"
      :columns="columns"
      :pagination="{ pageSize: listQuery.limit, total }"
      :scroll="{ y: 'calc(70vh)' }"
      row-key="id"
      size="small"
      @change="tableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="isDictCol(column.dataIndex)">
          {{ transformDict(record, column.dataIndex) }}
        </template>
        <template v-if="column.type === 21">
          <a-switch
            v-model="record[column.dataIndex]"
            @change="rowEdit(record)"
          />
        </template>
        <template v-if="column.type === 1">
          <span v-copyClipboard="record[column.dataIndex]">{{ record[column.dataIndex] }}</span>
        </template>
        <template v-if="column.type === 42">
          <span>{{ tags.filter(item => (record[column.dataIndex] || []).includes(item.id)).map(item => item.name) }}</span>
        </template>
        <template v-if="column.type === 48">
          <NtdParamsSelect
            v-model:defaultIds="record[column.dataIndex]"
            @ntdChange="rowEdit(record)"
          />
        </template>
        <template v-if="column.type === 163">
          <NtdImg :urls="[record[column.dataIndex]]" />
        </template>
        <template v-if="column.type === 15">
          <a-popover
            v-model="record.operVisible"
            title="操作"
            trigger="click"
          >
            <template #content>
              <a-button
                type="link"
                size="small"
                target="link"
                :href="record[column.dataIndex]"
              >
                跳转
              </a-button>
              <a-button
                v-copyClipboard="record[column.dataIndex]"
                type="link"
                size="small"
                @click="record.operVisible = false"
              >
                复制
              </a-button>
            </template>
            <a-button
              type="link"
              size="small"
            >
              {{ record[column.dataIndex] }}
            </a-button>
          </a-popover>
        </template>
        <template v-if="column.type === 3">
          <span v-dayjs="record[column.dataIndex]" />
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <template
            v-for="rowFun in tableRowFunctions"
            :key="rowFun.text"
          >
            <a-button
              type="link"
              size="small"
              @click="handleCustomerClick(record, rowFun)"
            >
              {{ rowFun.text }}
            </a-button>
          </template>
          <a-button
            type="link"
            size="small"
            @click="handleUpdate(record)"
          >
            编辑
          </a-button>
          <a-button
            type="link"
            size="small"
            @click="handleDelete(record)"
          >
            删除
          </a-button>
        </template>
      </template>
    </ATable>
    <AModal
      :title="dataForm && (dataForm.id ? '编辑' : '创建')"
      :visible="modalTag"
      :footer="null"
      width="80%"
      @cancel="modalTag = false"
    >
      <template v-if="dataForm && modalTag">
        <add-form
          :form="dataForm"
          :cancel="() => { modalTag = false }"
          :init-list="initList"
        />
      </template>
      <template v-else>
        您的表单数据不合法，请您联系系统管理员进行处理......
      </template>
    </AModal>
    <component
      :is="componentName"
      :key="componentName"
      ref="customerComp"
      :form="dataForm"
    />
    <div
      id="customer-component"
      class="page-fs"
      style="position: absolute; border: 0px solid red; top: 0; left: 0; z-index: -1"
    />
    <!--    <el-dialog title="预览" :visible="isPreviewDialog" width="70%">-->
    <!--      <div v-html="previewHtml" />-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import UtilAxios from '@/util/util-axios'
import UtilAnt from '@/config/frame/ant/util/util-ant'
import ContextModel from './context/context-model'
import CommonQueryTool from './components/common-query-tool'
import TableColumns from './components/table-columns'
import AddForm from './add'
import NtdImg from "@/components/ntd-img/NtdImg";
import useTags from "@/components/ntd-tags-select/useTags";
import NtdParamsSelect from '@/components/ntd-params-select/index';

let context
export default {
  components: {CommonQueryTool, AddForm, NtdImg, NtdParamsSelect},
  data() {
    return {
      dataForm: undefined,
      list: undefined,
      total: 50,
      attributes: undefined,
      modalTag: false,
      listQuery: {page: 0, limit: 20},
      disableFeatures: undefined, // 禁用配置信息
      isPreviewDialog: false, // 预览dialog状态
      previewHtml: '', // 预览内容
      rule: {},
      tableRowFunctions: [],
      componentName: '',
      customerModalTag: true,
      tags: [],
    }
  },
  computed: {
    columns() {
      return TableColumns.init(this.rule)
    }
  },
  async mounted() {
    await this.initModel()
    this.initTableRowFun()
    this.initList()
    this.initTags()
  },
  methods: {
    async initTags(ids = []) {
      this.tags = await useTags().initList();
    },
    async initModel() {
      context = await ContextModel.init(this.$route)
      this.rule = context.rule
      if (this.rule && this.rule.pageConfig) {
        this.listQuery.limit = this.rule.pageConfig.limit || 20
      }
      this.attributes = context.attributes
    },
    initTableRowFun() {
      this.tableRowFunctions = context.rule.tableRowFunctions || []
    },
    rowEdit(row) {
      context.api['edit'](row).then(() => UtilAnt.msg())
    },
    transformDict(record, dataIndex) {
      let dictList = this.rule.tableConfig[dataIndex].dictList
      if (!dictList) {
        return record[dataIndex]
      }
      let recordVals = record[dataIndex];
      if (!(recordVals instanceof Array)) {
        recordVals = [recordVals];
      }
      return recordVals.map(recordVal => {
        let dictRes = dictList.filter(dict => dict.val === recordVal)
        if (dictRes.length < 1) {
          return record[dataIndex]
        }
        return dictRes[0].name
      }).join(',')
    },
    handleCustomerClick(row, tableRowFun) {
      this.componentName = tableRowFun.component
      this.dataForm = {...row}
      this.$nextTick(() => {
        this.$refs.customerComp.open()
      })
    },
    tableChange(pag, filters, sorter) {
      this.listQuery.page = pag?.current
      this.initList()
    },
    initList(init = false, queryParams = []) {
      if (init === true) {
        this.listQuery.page = 0
      }
      this.listQuery.condition = UtilAxios.condition(queryParams)
      this.list = undefined
      context.api.list(this.listQuery).then(res => {
        this.list = res.records
        this.total = res.totalElements || res.total
        this.initTags();
      })
      this.rule.ruleInit && this.rule.ruleInit()
    },
    handleUpdate(rowData) {
      if (rowData !== undefined) {
        this.dataForm = {...rowData}
      } else {
        this.dataForm = {}
      }
      this.modalTag = true
    },
    handleDelete(row) {
      context.api.remove(row.id).then(() => {
        UtilAnt.msg('删除成功！')
        this.initList(true)
      })
    },
    isDictCol(key) {
      const config = this.rule.tableConfig[key]
      return config && config.dictList && config.dictList.length > 0
    }
  }
}
</script>
<style scoped>
.table-content {
  padding: 0;
}

.ant-table td {
  white-space: nowrap;
}
</style>
